<template>
  <div>
    采购明细页面<br/><br/>
    <!-- 条件查询表单 -->
    <div>
      <el-form :inline="true" :model="purOrderDetailVO" class="demo-form-inline">
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="订单编号">
              <el-input v-model="purOrderDetailVO.ordernum" placeholder="订单编号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商">
              <el-select v-model="purOrderDetailVO.supplier.sid" filterable  placeholder="请选择" clearable>
                <el-option v-for="item in suppliers" :key="item.sid" :label="item.sname" :value="item.sid" ></el-option>  
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="商品名称">
            <el-select v-model="purOrderDetailVO.purGoods.gid" filterable placeholder="请选择" clearable>
                <el-option v-for="item in purGoodss" :key="item.gid" :label="item.gname" :value="item.gid" ></el-option>  
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="商品类型">
            <el-select v-model="purOrderDetailVO.purGoods.gid" filterable placeholder="请选择" clearable>
                <el-option v-for="item in purGoodss" :key="item.gid" :label="item.productType" :value="item.gid" ></el-option>  
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="采购数量" class="priceFormItem" prop="minamount">
              <el-input v-model="purOrderDetailVO.minamount" class="priceInput" style="width: 70px; margin-right: 20px"/>-
              <el-input v-model="purOrderDetailVO.maxamount" class="priceInput" ref="maxamount" style="width: 70px; margin-left: 20px"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单价" prop="perprice">
              <el-input v-model="purOrderDetailVO.perprice" placeholder="单价"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="税率" prop="taxrate">
              <el-input v-model="purOrderDetailVO.taxrate" placeholder="税率"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="价税合计" class="priceFormItem" prop="minmtsum">
              <el-input v-model="purOrderDetailVO.minmtsum" class="priceInput" style="width: 70px; margin-right: 20px"/>-
              <el-input v-model="purOrderDetailVO.maxmtsum" class="priceInput" ref="maxmtsum" style="width: 70px; margin-left: 20px"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="开票状态">
              <el-select v-model="purOrderDetailVO.invoicestatus" placeholder="请选择订单状态">
                <el-option label="不限" value=""></el-option>
                <el-option label="未开发票" value="未开发票"></el-option>
                <el-option label="部分开票" value="部分开票"></el-option>
                <el-option label="全部开票" value="全部开票"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="已开票金额" class="priceFormItem" prop="mininvoiced">
              <el-input v-model="purOrderDetailVO.mininvoiced" class="priceInput" style="width: 70px; margin-right: 20px"/>-
              <el-input v-model="purOrderDetailVO.maxinvoiced" class="priceInput" ref="maxinvoiced" style="width: 70px; margin-left: 20px"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发票号">
              <el-input v-model="purOrderDetailVO.invoicenum" placeholder="发票号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="已付款金额" class="priceFormItem" prop="minpaid">
              <el-input v-model="purOrderDetailVO.minpaid" class="priceInput" style="width: 70px; margin-right: 20px"/>-
              <el-input v-model="purOrderDetailVO.maxpaid" class="priceInput" ref="maxpaid" style="width: 70px; margin-left: 20px"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="未付款金额" class="priceFormItem" prop="minunpaid">
              <el-input v-model="purOrderDetailVO.minunpaid" class="priceInput" style="width: 70px; margin-right: 20px"/>-
              <el-input v-model="purOrderDetailVO.maxunpaid" class="priceInput" ref="maxunpaid" style="width: 70px; margin-left: 20px"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="付款状态">
              <el-select v-model="purOrderDetailVO.paystatus" placeholder="请选择付款状态">
                <el-option label="不限" value=""></el-option>
                <el-option label="未付款" value="未付款"></el-option>
                <el-option label="部分付款" value="部分付款"></el-option>
                <el-option label="全部付款" value="全部付款"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="订单状态">
              <el-select v-model="purOrderDetailVO.orderstatus" placeholder="请选择订单状态">
                <el-option label="不限" value=""></el-option>
                <el-option label="未入库" value="未入库"></el-option>
                <el-option label="待入库" value="待入库"></el-option>
                <el-option label="已入库" value="已入库"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建时间">
              <el-date-picker v-model="purOrderDetailVO.createdate" type="date" placeholder="选择日期"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="getAllOrderButton">查询</el-button>
              <el-button type="info" icon="el-icon-refresh" @click="reset">重置</el-button>
              <!-- <el-button type="success" icon="el-icon-share" @click="reset">打印</el-button> -->
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item> </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary"  @click="getSumAmountButton">采购商品数量统计</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary"  @click="getSumMtsumButton">采购商品金额统计</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 数据展示 -->
    <div>
      <el-table :data="pageBean.beanList" style="widtindexh: 100%" :filter-method="filterHandler" :default-sort = "{prop: 'ordernum', order: 'descending'}">
        <el-table-column fixed type="index" label="序号" width="55" :index="Nindex"></el-table-column>
        <el-table-column fixed prop="ordernum" label="订单编号" width="170" sortable></el-table-column>
        <el-table-column fixed prop="purGoods.batchNumber" label="商品编码" width="170" sortable></el-table-column>
        <el-table-column fixed prop="purGoods.gname" label="商品名称" width="130" sortable></el-table-column>
        <el-table-column prop="purGoods.productType" label="商品类型" width="100" sortable></el-table-column>
        <el-table-column prop="supplier.sname" label="供应商名称" width="190"></el-table-column>
        <el-table-column prop="productUnit" label="单位" width="80" ></el-table-column>
        <el-table-column prop="summoney" label="购买金额/元" width="120" sortable></el-table-column>
        <el-table-column prop="amount" label="采购数量" width="120" sortable></el-table-column>
        <el-table-column prop="perprice" label="商品单价/元" width="120" sortable></el-table-column>
        <el-table-column prop="taxrate" label="税率%" width="120" sortable></el-table-column>
        <el-table-column prop="mtsum" label="价税合计/元" width="120" sortable></el-table-column>
        <el-table-column prop="paystatus" label="发票状态" width="100"
          :filters="[{ text: '未开发票', value: '未开发票' }, { text: '部分开票', value: '部分开票' },{ text: '全部开票', value: '全部开票' }]" :filter-method="filterInvoicestatus" filter-placement="bottom-end">
          <template slot-scope="scope">
            <el-tag :type="scope.row.invoicestatus === '全部开票' ? 'success' : scope.row.invoicestatus === '部分开票' ? 'primary' : 'danger'" disable-transitions>{{scope.row.invoicestatus}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="invoiced" label="已开金额/元" width="120" sortable></el-table-column>
        <el-table-column prop="uninvoice" label="已开金额/元" width="120" sortable></el-table-column>
        <el-table-column prop="invoicenum" label="发票号" width="170" sortable></el-table-column>
        <el-table-column prop="sinvicedate" label="开票日期" width="120" sortable></el-table-column>
        <el-table-column prop="paid" label="已付款/元" width="120" sortable></el-table-column>
        <el-table-column prop="unpaid" label="未付款/元" width="120" sortable></el-table-column>
        <el-table-column prop="paydate" label="付款日期" width="120" sortable></el-table-column>
        <el-table-column prop="paystatus" label="付款状态" width="100"
          :filters="[{ text: '未付款', value: '未付款' }, { text: '部分付款', value: '部分付款' },{ text: '全部付款', value: '全部付款' }]" :filter-method="filterPaystatus" filter-placement="bottom-end">
          <template slot-scope="scope">
            <el-tag :type="scope.row.paystatus === '全部付款' ? 'success' : scope.row.paystatus === '部分付款' ? 'primary' : 'danger'" disable-transitions>{{scope.row.paystatus}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="orderstatus" label="订单状态" width="100"
          :filters="[{ text: '未入库', value: '未入库' }, { text: '待入库', value: '待入库' },{ text: '已入库', value: '已入库' }]" :filter-method="filterOrderstatus" filter-placement="bottom-end">
          <template slot-scope="scope">
            <el-tag :type="scope.row.orderstatus === '已入库' ? 'success' : scope.row.orderstatus === '待入库' ? 'primary' : 'danger'" disable-transitions>{{scope.row.orderstatus}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" prop="createdate" label="创建时间" width="150"></el-table-column>
      </el-table>
    </div>

    <!-- 分页控件 -->
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageIndex"
        :page-sizes="[3, 5, 7]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageBean.totalRecord">
      </el-pagination>
    </div>
  </div>
</template>
<script>

export default {
  data() {
    //校验单价
    const twoPoint = (rule, value, callback) => {
      if(/^\d+\.?\d{0,2}$/.test(value)){
        if(value.indexOf('.')=='-1'&&value.length>1&&value.slice(0,1)=='0'){
          callback(new Error("最多包含两位小数的正数且不能为以0开头的正整数"));
        }
      }else{
        callback(new Error("最多包含两位小数的正数且不能为以0开头的正整数"));
      }
    };
    return {
      //定义验证规则
      rules: {  
        supplier:[{required: true,message: '请选择供应商', trigger: 'blur'}], 
        orderdate: [{required: true, message: '请输入订货日期', trigger: 'blur'}],
        demanddelivery: [{required: true, message: '请输入要求交期', trigger: 'blur'}],
        deliverytype:[{required: true, message: '请输入交货方式', trigger: 'blur' }],
        productUnit:[{required: true,message: '请选择单位', trigger: 'blur'}],
        perprice:[
          {required: true, message: "请输入单价", trigger: "blur,change"},
          { min: 1, max: 6, message: '长度在 1 到 6 个字符', trigger: 'blur,change' },
          { validator: twoPoint, message: '最多包含两位小数的正数且不能为以0开头的正整数', trigger: 'blur' }
          ],
        amount:[
          {required: true,message: '请输入采购数量', trigger: 'blur' },
          {"pattern": /^[0-9]*$/,"message": "数量为≥1的正整数"}
        ],
        taxrate:[{required:false , message:'请输入100以内数字'},{
            pattern: new RegExp(/^(?:0|[1-9][0-9]?|100)(\.[0-9]{0,2})?$/,'g'),
            message: '请输入100以内数字'}],
      },
      
      dialogFormTitle:"",
      sample: {},
      pageBean: [],
      pageIndex: 1,
      pageSize: 5,
      purOrderDetailVO: {supplier:{sid:null},purGoods:{gid:null}},
      suppliers:[],
      purOrderAdd:{ supplier:{sid:null}, purGoods:{gid:null}},
      purGoodss:[],
      perprice: '', 
      amount: '', 
      dialogFormVisible: false,
      
      //pages: ""
    };
  },
  mounted() {
    this.getAllOrder();
    this.getAllSupplier();
    this.getAllPurGoods();
  },
  computed:{
    //计算合价
    summoney() {
      if (this.purOrderAdd.perprice === '' && this.purOrderAdd.amount === '' ) {
        return 0
      } else {
        return Number(this.purOrderAdd.perprice) * Number(this.purOrderAdd.amount) * Number(this.purOrderAdd.taxrate*0.01+1.00)
      }
    },
    //自动生成订单号
    generateOrderNumber() {
      const date = new Date();
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      const seconds = date.getSeconds().toString().padStart(2, '0');
      const milliseconds = date.getMilliseconds().toString().padStart(3, '0');
      return `${year}${month}${day}${hours}${minutes}${seconds}${milliseconds}`;
    },
  },

  methods: {
    //统计采购商品总金额
    getSumMtsumButton(){
      this.$axios.get("/purorderdetail/getSumMtsum").then((resp) => {
        // this.$message({
        //   message:JSON.stringify(resp.data.msg),
        //   type:'success'
        // })
        this.$notify({
          title: '采购商品总金额',
          message: JSON.stringify(resp.data.msg),
        });
      })  
    },
    //统计采购商品总数量
    getSumAmountButton(){
      this.$axios.get("/purorderdetail/getSumAmount").then((resp) => {
        // this.$message({
        //   message:JSON.stringify(resp.data.msg),
        //   type:'success'
        // })
        this.$notify({
          title: '采购商品总数量',
          message: JSON.stringify(resp.data.msg),
        });
      })
    },
    
    //校验正整数
    ceshi(val){
        this.purOrderAdd.amount = this.purOrderAdd.amount.replace(/\D/g, '');
		    if(this.purOrderAdd.amount ==0){
			      this.purOrderAdd.amount = '';
		   }
    },
    //表格区分开票状态
    filterInvoicestatus(value, row) {
      return row.invoicestatus === value;
    },

    //表格区分付款状态
    filterPaystatus(value, row) {
        return row.orderstatus === value;
    },
    
    //表格区分已入库和未入库
      filterOrderstatus(value, row) {
          return row.orderstatus === value;
      },
      //表格下拉箭头筛选已入库和未入库
      filterHandler(value, row, column) {
        const property = column['property'];
        return row[property] === value;
      },

    //查询所有商品
     getAllPurGoods() {
      this.$axios.get("/purgoods/findAll").then((resp) => {
        this.purGoodss = resp.data.data;
      });
    },
    //查询所有供应商
    getAllSupplier() {
      this.$axios.get("/supplier/findAll").then((resp) => {
        this.suppliers = resp.data.data;
      });
    },

    //模态框关闭执行
    closeDialog() {
      //清空数据
      this.purOrderAdd = { supplier:{sid:null}, purGoods:{gid:null}};
      //清空前端验证提示
    },

    //条件查询操作
    getAllOrderButton() {
      this.pageIndex = 1;
      this.pageSize = 5;
      this.getAllOrder();
    },

    //重置按钮
    reset() {
      this.purOrderDetailVO={supplier:{sid:null}, purGoods:{gid:null}};
      this.getAllOrder();
    },

    //删除操作
    deleteSupplier(index, row) {
      this.$confirm("此操作将永久删除该供应商, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
      .then(() => {
        this.$axios.post("/supplier/getnumPurReqAndSupplierBySid/"+ row.sid).then((resp) => {
          if(true){
            this.$axios.post("/supplier/removeBySid/"+ row.sid).then((resp) => {
              if (resp.data.code == 200) {
                this.$message({
                type: "success",
                message: "删除成功!",
              });
                //起到刷新页面的作用
                this.getAllOrder();
              }else{
                this.$message("该供应商下存在商品，不能删除");
              }
            });
          }
        });
      })
      .catch(() => {
        this.$message({
          type: "info",
          message: "已取消删除",
        });
      });
    },
    //编辑采购订单信息
    handleEdit(index, row) {
      this.dialogFormVisible = true;
      this.dialogFormTitle = "修改采购订单";
      //浅拷贝，将row行的数据拷贝到smapleModify中
      this.purOrderAdd = { ...row };
    },
    //查看订单详情
    orderDetail(index, row) {
      this.dialogFormVisible = true;
      this.dialogFormTitle = "采购订单详情";
      //浅拷贝，将row行的数据拷贝到smapleModify中
      this.purOrderAdd = { ...row };
    },

    // addOrder(formName) {
    //   this.dialogFormVisible = false;
    //   if (this.dialogFormTitle == "添加采购订单") {
    //     this.purOrderAdd.ordernum = this.generateOrderNumber;
    //       this.$axios
    //         .post("/purorder/addOrderList", this.purOrderAdd)
    //         .then((resp) => {
    //           if (resp.data.code == 200) {
    //             alert("添加成功");
    //             //起到刷新页面的作用
    //             this.getAllOrder();
    //           }else {
    //             this.$message(JSON.stringify(resp.data.msg));
    //           }
    //         });
    //   }
    // },

     //新增采购订单
    // addOrder(formName,generateOrderNumber) {
    //   console.log("添加order" + JSON.stringify(this.purOrderAdd));
    //     this.$refs[formName].validate((valid) => {
    //       if (valid) {
    //         this.dialogFormVisible = false;
    //         if (this.dialogFormTitle == "修改采购订单") {
    //           this.$axios
    //           .post("/purorder/modifyOrderList", this.purOrderAdd)
    //           .then((resp) => {
    //             if (resp.data.code == 200) {
    //               alert("修改成功");
    //               //起到刷新页面的作用
    //               this.getAllOrder();
    //             } else {
    //               this.$message(JSON.stringify(resp.data.msg));
    //             }
    //           });
    //         }else{
    //           this.purOrderAdd.ordernum = this.generateOrderNumber;
    //           this.$axios
    //             .post("/purorder/addOrderList", this.purOrderAdd)
    //             .then((resp) => {
    //               if (resp.data.code == 200) {
    //                 alert("添加成功");
    //                 //起到刷新页面的作用
    //                 this.getAllOrder();
    //               }else {
    //                 this.$message(JSON.stringify(resp.data.msg));
    //               }
    //             });
              
    //         }
    //        } else {
    //          this.$message("前端验证失败");
    //          return false;
    //        }
    //      });   
    //    },
    
    //新增采购订单
    addOrder(formName,generateOrderNumber) {
      console.log("添加order" + JSON.stringify(this.purOrderAdd));
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.dialogFormVisible = false;
            if (this.dialogFormTitle == "添加采购订单") {
              this.purOrderAdd.ordernum = this.generateOrderNumber;
              this.$axios
                .post("/purorder/addOrderList", this.purOrderAdd)
                .then((resp) => {
                  if (resp.data.code == 200) {
                    alert("添加成功");
                    //起到刷新页面的作用
                    this.getAllOrder();
                  }else {
                    this.$message(JSON.stringify(resp.data.msg));
                  }
                });
            }
          } else {
            this.$message("前端验证失败");
            return false;
          }
         }); 
            if (this.dialogFormTitle == "添加采购订单") {
              this.purOrderAdd.ordernum = this.generateOrderNumber;
              this.$axios
                .post("/purorder/addOrderList", this.purOrderAdd)
                .then((resp) => {
                  if (resp.data.code == 200) {
                    this.dialogFormVisible = false;
                    alert("添加成功");
                    //起到刷新页面的作用
                    this.getAllOrder();
                  }else {
                    this.$message(JSON.stringify(resp.data.msg));
                  }
                });
            }else{
              this.$axios
              .post("/purorder/modifyOrderList", this.purOrderAdd)
              .then((resp) => {
                if (resp.data.code == 200) {
                  alert("修改成功");
                  //起到刷新页面的作用
                  this.getAllOrder();
                } else {
                  this.$message(JSON.stringify(resp.data.msg));
                }
              });
            }
       },

      //重置
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },

    //条件查询订单
    onSubmit() {
      this.pageIndex = 1;
      this.getAllOrder();
    },

    //查询所有采购订单
    getAllOrder() {
      this.$axios.post("/purorderdetail/getOrderDetailList/" + this.pageIndex + "/" + this.pageSize,this.purOrderDetailVO)
        .then((resp) => {
          if(resp.data.code==200){
            this.pageBean = resp.data.data;
          }
        });
    },
    
    //分页，连续的序号
    Nindex(index) {
      // 当前页数 - 1 * 每页数据条数 + 1
      const pageIndex = this.pageIndex // 当前页码
      const pageSize = this.pageSize // 每页条数
      return index + 1 + (pageIndex - 1) * pageSize
    },
    //每页显示几条数据
    handleSizeChange(val) {
      this.pageSize = val;
      this.getAllOrder();
    },

    //显示第几页
    handleCurrentChange(val) {
      this.pageIndex = val;
      this.getAllOrder();
    },
  },
};
</script>

<style>

</style>